import router from './router'
import NProgress from 'nprogress'
import store from './store'
import 'nprogress/nprogress.css' // 固定搭配
import { getCookie } from './plugins/tools'
import { setDocumentTitle } from './config/tools'
NProgress.configure({ showSpinner: false })
const routerWhiteList = ['Login']
router.beforeEach((to, from, next) => {
  NProgress.start()
  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(to.meta.title))
  if (getCookie('Access-Token')) {
    if (to.path === '/login') {
      next({ path: '/index' })
      NProgress.done()
    } else {
      // 检测用户权限是否为空
      if (store.getters.menus.length === 0) {
        store.dispatch('getUserRouterRoles').then(roles => {
          console.log(roles)
          next({ ...to, replace: true })
        })
      } else {
        next()
      }
    }
  } else {
    if (routerWhiteList.includes((to.name))) {
      // 白名单中直接通过
      next()
    } else {
      next({ path: '/login', query: { redirect: to.fullPath } })
    }
  }
})
router.afterEach(() => {
  NProgress.done()
  // const title = store.getters['tags/currentTag'].name
  // router.$userRouter.setTitle(title)
})
export default router
